package com.ifcar.app.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;

import com.ifcar.app.util.StringUtil;
import com.ifcar.app.util.Tools;
import com.ifcar.app.activity.R;

public class AccountRegister extends BaseActivity{

	private EditText regUserName;
	private EditText regPassword;
	private Button regSubmit;
	private boolean loginsuccess;
	
	private ProgressDialog proDialog;
	private String username;
	private String password;
	private String rst;
	private CheckBox register_box;
	
	private final int UNACTIVIENET = 0; // 网络异常
	private final int USERNAMENULL = 1; // 用户名为空
	private final int INVALIDUSERNAME = 2; // 用户名不合法
	private final int PASSWORDNULL = 3; // 密码为空
	private final int INVALIDPASSWORD = 4; // 密码不合法
	private final int REGSUCCESS = 5; // 注册成功
	private final int USEREXIST = 6; // 用户名已存在
	private final int REGFAIL = 7; // 注册失败
	private final int REGACCOUNTINVAILD = 8; // 用户名不合法（注册服务器验证）
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.accountregister);
		findViewsById();
		
		regSubmit.setOnClickListener(registerListener);
		register_box.setOnCheckedChangeListener(passwordVisiblyListener);
		
		regUserName.requestFocus();
		InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
		imm.showSoftInput(regUserName, 0);
		
	}
	
	/** 初始化注册View组件 */
	private void findViewsById() {
		regUserName = (EditText) findViewById(R.id.regusername);
		regPassword = (EditText) findViewById(R.id.regpassword);
		regSubmit = (Button) findViewById(R.id.do_reg_button);
		
		register_box = (CheckBox)findViewById(R.id.register_box);
	}
	
	/**注册*/
	private OnClickListener registerListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			username = regUserName.getText()==null?"":regUserName.getText().toString();
			password = regPassword.getText()==null?"":regPassword.getText().toString();
			
			if(checkAccountInfor()){
				if(Tools.CheckNetwork(AccountRegister.this)){
					proDialog = ProgressDialog.show(AccountRegister.this, "","正在注册...", true, true);
					Thread registerThread = new Thread(new RegisterHandler());
					registerThread.start();
				}else{
					registerHandler.sendEmptyMessage(UNACTIVIENET);
				}
			}
			
		}
	};
	
	/**显示密码*/
	private OnCheckedChangeListener passwordVisiblyListener = new OnCheckedChangeListener() {
		
		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

			if(isChecked){
				regPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
			}else{
				regPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
			}
		}
	};
	
	private boolean checkAccountInfor(){
		boolean result = false;
		
		if("".equals(username) || null == username){
			registerHandler.sendEmptyMessage(USERNAMENULL);
		}else if("".equals(password) || null == password){
			registerHandler.sendEmptyMessage(PASSWORDNULL);
		}else{
			
			Pattern pattern = Pattern.compile("^[a-zA-Z]+[a-zA-Z0-9_]{4,16}[a-zA-Z0-9]+$");
			Matcher matcher = pattern.matcher(username);
			if(!matcher.find() || username.length()<6 || username.length()>18){ // 用户名合法
				registerHandler.sendEmptyMessage(INVALIDUSERNAME);
			}else if(password.length()<6 || password.length()>16){ // 密码合法
				registerHandler.sendEmptyMessage(INVALIDPASSWORD);
			}else{
				result = true;
			}
			
		}
		
		return result;
	}
	
	public void goBackClick(View view){
		finish();
	}

	@Override
	protected void onDestroy() {
		if(null!=proDialog&&proDialog.isShowing())
			proDialog.dismiss();
		super.onDestroy();
	}
	
	/** 登录后台通知更新UI线程,主要用于注册失败,通知UI线程更新界面 */
	Handler registerHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			
			if (proDialog != null) {
				proDialog.dismiss();
			}
			
			switch (msg.what) {
			case UNACTIVIENET:
				Tips("网络异常，请检查网络");
				break;

			case USERNAMENULL:
				Tips("用户名不能为空");
				break;
				
			case PASSWORDNULL:
				Tips("密码不能为空");
				break;

			case INVALIDUSERNAME:
				Tips("用户名不合法");
				break;

			case INVALIDPASSWORD:
				Tips("密码不合法");
				break;
				
			case USEREXIST:
				Tips("用户名已经存在");
				break;
				
			case REGACCOUNTINVAILD:
				Tips("用户名不合法");
				break;
				
			case REGFAIL:
				Tips("注册失败,请稍候尝试");
				break;
				
			case REGSUCCESS:

				Tips("注册成功");
				
				Intent i = new Intent(AccountRegister.this, AccountLogin.class);
				
				Bundle b = new Bundle();
				b.putString("username", username);
				b.putBoolean("isRegister", true);
				i.putExtras(b);
				
				startActivity(i);
				
				AccountRegister.this.finish();
				
				break;
			}
		}
	};
	
	private void Tips(String message){
		Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
	}
	
	class RegisterHandler implements Runnable {
		
		public void run() {
			
			username = regUserName.getText().toString();
			password = regPassword.getText().toString();
			DefaultHttpClient regclient = null;
			try {
				HttpPost httpRequest = new HttpPost(StringUtil.REGISTERURL);

				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("username", username));
				params.add(new BasicNameValuePair("password", password));
				
				// 添加请求参数到请求对象
				httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
				
				HttpParams httpParameters = new BasicHttpParams();
				// Set the timeout in milliseconds until a connection is
				// established.
				int timeoutConnection = 60000;
				HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
				// Set the default socket timeout (SO_TIMEOUT)
				// in milliseconds which is the timeout for waiting for data.
				int timeoutSocket = 60000;
				HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
				regclient = new DefaultHttpClient(httpParameters);
				Tools.setHttpClientHostProxy(regclient, AccountRegister.this);
				
				HttpResponse httpResponse = regclient.execute(httpRequest);
				
				if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					
					String status = EntityUtils.toString(httpResponse.getEntity());

					String resultString = status.substring(0, 3);
					
					if("200".equals(resultString)){
						loginsuccess  = true;
						registerHandler.sendEmptyMessage(REGSUCCESS);
					}else if("401".equals(resultString)){
						loginsuccess  = false;
						registerHandler.sendEmptyMessage(REGACCOUNTINVAILD);
					}else if("421".equals(resultString)){
						loginsuccess  = false;
						registerHandler.sendEmptyMessage(USEREXIST);
					}else{
						loginsuccess  = false;
						registerHandler.sendEmptyMessage(REGFAIL);
					}
					
				} else{
					loginsuccess  = false;
					registerHandler.sendEmptyMessage(REGFAIL);
				}

			} catch (Exception e) {
				registerHandler.sendEmptyMessage(REGFAIL);
				e.printStackTrace();
			}finally {
				if(null!=regclient)
					regclient.getConnectionManager().shutdown();
			}
		}
	}
}
